package com.emm.yixun.openapi.aop;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.app.LoginReqDto;
import com.emm.yixun.common.enums.SourceTypeEnum;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.appDto.ParamsBody;
import com.emm.yixun.common.model.dto.LogDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.openapi.anotations.UserOperationLog;
import com.emm.yixun.openapi.hander.LoginHander;
import com.emm.yixun.system.service.LogServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;

@Aspect    
@Component  
public class UserOperationLogAdvisor {
	private static Log logger = LogFactory.getLog(UserOperationLogAdvisor.class);
	
	@Autowired
	private LogServiceFacade logServiceFacade;
	
	@Autowired
	private LoginHander loginHander;
	
	@Autowired
	private UserServiceFacade userServiceFacade;
	
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	 @Pointcut("@annotation(com.emm.yixun.openapi.anotations.UserOperationLog)")    
	 public void controllerAspect(){}
	 /**
	 * 方法描述 : IOS,安卓 系统日志
	 * 创建者：ThinkPad 
	 * 项目名称： emm-openapi
	 * 类名： UserOperationLogAdvisor.java
	 * 版本： v1.0
	 * 创建时间： 2016年11月17日 下午1:54:37
	 * @param joinPoint void
	  */
	@SuppressWarnings("static-access")
	@Before("controllerAspect()")    
	 public  void doBefore(JoinPoint joinPoint) { 
		 try {
			
			 //得到注解
			 Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
			 UserOperationLog operateLog = method.getAnnotation(UserOperationLog.class);
			 
			 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			 String body = request.getParameter("body");
			 JSONObject json = new JSONObject();
			 JSONObject resJson = json.parseObject(body);
			 ParamsBody paramsBody = null;
			 if(operateLog.isLogin()){
				 LoginReqDto loginReqVo =JSONObject.parseObject(resJson.get("params").toString(), LoginReqDto.class);
				 //调用登录
				 Response<User> user = userServiceFacade.login(null, loginReqVo.getLoginName(), loginReqVo.getLoginPwd());
				 if(user.isSuccess()){
					 paramsBody = new ParamsBody(user.getEntity().getId(), user.getEntity().getMerchantId(), null, loginReqVo.getTerminalCode());
				 }
			 }else{
				 paramsBody = JSONObject.parseObject(resJson.get("params").toString(), ParamsBody.class);
			 }
				 logger.info("--------记录日志开始----");
				 LogDto logdto = new LogDto();
				 Response<Project> response = new Response<Project>(true);
				 if(paramsBody.getProjectCode() != null && !"".equals(paramsBody.getProjectCode())){
					 response = projectServiceFacade.findProjectByCode(paramsBody.getProjectCode());
				 }
				 if(response.isSuccess()){
					 logdto.setMerchantId(paramsBody.getMerchantId());
					 logdto.setCreateUserId(paramsBody.getUserId());
					 logdto.setCreateTime(new Date());
					 logdto.setUpdateTime(new Date());
					 logdto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					 if(response.getEntity() != null){
						 logdto.setProjectId(response.getEntity().getId());
					 }
					 logdto.setModelName(operateLog.getModelName().getModelName());
					 logdto.setFunctionName(operateLog.getFunctionName().getFunctionTypeName());
					 String[] terminalCode = paramsBody.getTerminalCode().split("\\|");
					 if(terminalCode[1].equals("1")){
						 logdto.setSourceType(SourceTypeEnum.SOURCETYPE_2.getSourceType());
					 }else {
						 logdto.setSourceType(SourceTypeEnum.SOURCETYPE_1.getSourceType());
					 }
					 logServiceFacade.save(logdto);
				 }
				 logger.info("--------记录日志结束----");
			
		} catch (Exception e) {
			logger.error("记录日志,系统异常:"+e);
		}
	 }
		
}
